package com.nuanshui.heatedloan.baseservice.rongyun.savehistory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.mongodb.BasicDBObject;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.framework.utils.mongo.MongoManager;
import com.nuanshui.heatedloan.baseservice.rongyun.RongyunFacade;
import com.nuanshui.heatedloan.baseservice.rongyun.models.DownLoadHistroyModule;
import com.nuanshui.heatedloan.baseservice.rongyun.models.FormatType;
import com.nuanshui.heatedloan.baseservice.rongyun.models.MessageHistoryModule;
import com.nuanshui.heatedloan.baseservice.rongyun.models.SdkHttpResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

@Service
public class UserChatMessageHistoryService {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	//保存了聊天记录的mongo表
	public static final String MSGSAVECOLLECTION = "msgsavecollection";
	
	//临时保存文件
	private String savePath = System.getProperty("user.home")+File.separator+"msgTempDir";
	
	@Autowired
	private MongoManager mongoManager;
	
	public void saveMessageHistory(){
		//首先，先去下载当天的聊天记录
		List<DownLoadHistroyModule> histroy_url = getTodayChatMessageUrl();
		
		if(histroy_url.isEmpty()){
			LogUtil.info(logger,"今天没有聊天记录");
			return ;
		}
		//然后拿着url去下载文件
		List<File> zipFiles = downChatMessageZip(histroy_url);
		
		if(zipFiles.isEmpty()){
			return ;
		}
		
		//然后将下载的File文件进行解析
		List<MessageHistoryModule> messageHistoryModules = analysisZipToMessageModule(zipFiles);
		
		//然后将解析出来的对象进行保存
		saveMsgHistoryToMongo(messageHistoryModules);
		
		//删除零食文件
		deleteTempFile(zipFiles);

		LogUtil.info(logger, "-----------------------------------------------下载聊天记录任务完成-----------------------------------------------");
	}

	private void deleteTempFile(List<File> zipFiles) {
		int file_size = zipFiles.size();
		
		try {
			//休眠一下，然后删除，否则可能由于GC没有回收流，这里是删除不成功的
			Thread.sleep(1000 * 60);
			//将文件删除
			LogUtil.info(logger,"------------本次需要删除的文件总数为-- " + file_size + "--个文件---");
			for(int i=0; i<file_size; i++){
				File zip_file = zipFiles.get(i);
				if(zip_file.exists()){
					LogUtil.info(logger,"当前删除的是第----" + i +"---个文件，删除---" +(zip_file.delete() ? "成功~~~" : "失败!!!"));
					//如果删除失败，则退出时候删除。
					if(!zip_file.delete()){
						zip_file.deleteOnExit();
					}
				}
				
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void saveMsgHistoryToMongo(List<MessageHistoryModule> messageHistoryModules) {
		
		if(messageHistoryModules.isEmpty()){
			LogUtil.info(logger, "解析出来的对象是空的！");
			return ;
		}
		int size = messageHistoryModules.size();
		
		LogUtil.info(logger, "一共需要保存的聊天记录总数为----------"+ size + "----------次");
		
		for(int i=0; i< size; i++ ){
			MessageHistoryModule messageHistoryModule = messageHistoryModules.get(i);
			LogUtil.info(logger, "本次保存的聊天记录的第--------"+1+"-------保存的时间是--" + messageHistoryModule.getDateTime()+ "---msgUID是--" + messageHistoryModule.getMsgUID());
			
			BasicDBObject basicDBObject = new BasicDBObject(JSON.parseObject(JSON.toJSONString(messageHistoryModule)));
			mongoManager.save(MSGSAVECOLLECTION, basicDBObject);
		}
		
	}

	private List<MessageHistoryModule> analysisZipToMessageModule(List<File> zipFiles) {
		int file_size = zipFiles.size();
		List<MessageHistoryModule> modules = new ArrayList<MessageHistoryModule>(file_size);
		ZipFile zf = null;
		InputStream in = null;
		ZipInputStream zin = null;
		ZipEntry ze = null;
		BufferedReader br = null;
		LogUtil.info(logger,"------------本次进行解析的文件总数为-- " + file_size + "--个文件");
		try {
			//先解析文件
			for(int i=0; i<file_size; i++){
				File zip_file = zipFiles.get(i);
				
				zf = new ZipFile(zip_file);
				in = new BufferedInputStream(new FileInputStream(zip_file));
				zin = new ZipInputStream(in); 
				
				while ((ze = zin.getNextEntry()) != null) {    
					if (ze.isDirectory()) {  
						
					} else {
						LogUtil.info(logger,"当前进行解析的是第---"+i+"-----个文件，文件名字-- " + ze.getName() + " 文件大小为--"+ ze.getSize() + " bytes");
						
						long size = ze.getSize();    
						
						if (size > 0) {
							//读文件,获取到这个zip包里面的每一个json数据
							br = new BufferedReader(new InputStreamReader(zf.getInputStream(ze)));
							List<String> zip_values = new ArrayList<String>();
							String line;
							
							while ((line = br.readLine()) != null) {   
								
								//由于前面有一段的时间，所以这里截取了去
								int index = line.indexOf("{");
								if(index == -1) continue;
								line = line.substring(index);
								zip_values.add(line);
							}
							
							//将读到的文件进行解析
							int zip_value_josncount = zip_values.size();
							
							for(int j=0; j< zip_value_josncount; j++ ){
								
								String zip_value = zip_values.get(j);
								if(SysStringUtils.isEmpty(zip_value)){
									LogUtil.info(logger,"解析" + ze.getName() + " 文件时,读取文件失败！文件里面没有数据！");
									continue;
								}
								
								LogUtil.info(logger,"开始解析"+ze.getName()+"文件数据为JSON对象---------------------");
								LogUtil.info(logger,ze.getName()+"文件的数据为:\n" + zip_value + "\n");
								MessageHistoryModule historyModule = null;
								
								try{
									historyModule = JSON.parseObject(zip_value, MessageHistoryModule.class);
								}catch(JSONException e){
									LogUtil.info(logger,"解析" + ze.getName()+"文件的数据发生错误！错误信息" + e.getMessage());
									continue;
								}
								modules.add(historyModule);
							}
						 
						}    
		           }    
		       }    
	     }
		}catch (Exception e) {
				e.printStackTrace();
		}finally{
			try{
				br.close();
				zf.close();
				in.close();
				zin.closeEntry();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		return modules;
	}

	private List<File> downChatMessageZip(List<DownLoadHistroyModule> histroyModules) {
		
		List<File> files = new ArrayList<File>(histroyModules.size());
		FileOutputStream fos = null;
		InputStream inputStream = null;
		int size = histroyModules.size();
		LogUtil.info(logger, "---------------本次要下载的聊天记录zip包总数为" + size + "个文件");
		
		try {
			for(int i=0; i<size; i++){
				DownLoadHistroyModule histroyModule = histroyModules.get(i);
				
				if(SysStringUtils.isEmpty(histroyModule.getUrl()))
					continue;
				
				LogUtil.info(logger, "开始第----"+i+"次下载，--本次下载的聊天记录的地址为--" + histroyModule.getUrl());
				
				URL url = new URL(histroyModule.getUrl());
				HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
				//设置超时间为3秒  
				conn.setConnectTimeout(3*1000); 
				//防止屏蔽程序抓取而返回403错误  
				conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
				 //得到输入流  
				inputStream = conn.getInputStream();
		        //获取字节数组
		        byte[] getData = readInputStream(inputStream);
		        
		      //文件保存位置  
		      File saveDir = new File(savePath);
		      if(!saveDir.exists()){
		    	  saveDir.mkdir();
		      }
		      
		      String saveName = histroyModule.getDate()+".zip";
		      File file = new File(saveDir+File.separator+saveName);  
		      
		      fos = new FileOutputStream(file);       
		      fos.write(getData);
		      fos.flush();
		      files.add(file);
			} 
				
		}catch (Exception e) {
			e.printStackTrace();
			
		}finally{
		 if(fos!=null){  
            try {
				fos.close();
				if(fos!=null)
					inputStream.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}    
	      }
		}
		return files;
	}

	private byte[] readInputStream(InputStream inputStream) throws Exception {
		byte[] buffer = new byte[1024];    
        int len = 0;    
        ByteArrayOutputStream bos = new ByteArrayOutputStream();    
        while((len = inputStream.read(buffer)) != -1) {    
            bos.write(buffer, 0, len);    
        }    
        bos.close();    
        return bos.toByteArray();  
	}

	//获取到当前聊天记录的下载地址
	private List<DownLoadHistroyModule> getTodayChatMessageUrl() {
		
		List<DownLoadHistroyModule> chat_message_url = new ArrayList<DownLoadHistroyModule>(24);
		
		try {
			//得到前一天的年月日
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DATE, -1);
			Date date = cal.getTime();
			
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
			
			//生成date参数
			for(int i=1; i<=24; i++){
				
				String format_date = format.format(date);
				//格式问题
				if(i<10){
					format_date += 0+""+i;
				}else{
					format_date += i; 
				}
				
				LogUtil.info(logger, "本次下载的聊天记录的传入的时间为--" + format_date);
				SdkHttpResult result = RongyunFacade.getMessageHistoryUrl("tdrvipksr8za5","RT5agS9z75ycW",format_date,FormatType.json);
				
				//得到返回的参数
				String response_result = result.getResult();
				
				//封装成对象，得到下载地址
				DownLoadHistroyModule downLoadHistroyModule = JSON.parseObject(response_result, DownLoadHistroyModule.class);
				if(!downLoadHistroyModule.getCode().equals("200")){
					LogUtil.info(logger, "获取下载地址失败！错误码--"+ downLoadHistroyModule.getCode());
					continue;
				}
				
				LogUtil.info(logger, "本次下载的聊天记录的返回的时间为--" + downLoadHistroyModule.getDate());
				
				
				if(SysStringUtils.isEmpty(downLoadHistroyModule.getUrl())){
					LogUtil.info(logger, format_date +"--时间段并没有聊天记录数据~~~~~");
					continue;
				}
				
				chat_message_url.add(downLoadHistroyModule);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return chat_message_url;
	}
}
